/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.edn.pecera.client.comms;

import es.edn.pecera.client.Alimento;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import java.io.*;
import java.text.MessageFormat;
import org.apache.commons.httpclient.params.HttpClientParams;

/**
 *
 * @author jorge
 */
public class DownloadManager {

    public DownloadManager() {
    }
    String url = "http://localhost:8080/pecera/download/downloadContent";

    public Alimento download(String uuid, String id) {
        long localFileSize = 0;
        long remoteFileSize = 0;
        BufferedInputStream in = null;
        RandomAccessFile out = null;
        HttpMethod request = null;

        try {
            File file = new File(uuid + ".zip");
            if (file.exists()) {
                localFileSize = file.length();
            }

            HttpClient client = new HttpClient();
            request = new GetMethod(url+"?uuid="+uuid+"&id="+id);
            if (localFileSize > 0) {
                // server must support partial content for resume
                request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
                if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
                    return null;
                }
            } else {
                int result = client.executeMethod(request);
                System.out.println("result "+result+ " "+request.getURI());
                if (result != HttpStatus.SC_OK) {
                    return null;
                }
            }

            Header contentLengthHeader = request.getResponseHeader("content-length");
            if (contentLengthHeader == null) {
                return null;
            }
            remoteFileSize = Long.parseLong(contentLengthHeader.getValue());

            Alimento ret = new Alimento();
            ret.setPosterior(request.getResponseHeader("Pecera-postcmd").getValue());

            in = new BufferedInputStream(request.getResponseBodyAsStream());
            out = new RandomAccessFile(file, "rw");
            out.seek(localFileSize);

            int offset = 0;
            int len = 4096;
            int bytes = 0;

            byte[] block = new byte[len];
            if ((bytes = in.read(block, offset, len)) > -1) {
                out.write(block, 0, bytes);
            }
            ret.setContent(file);
            return ret;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
            request.releaseConnection();
        }
    }

}
